/**
 * Copyright 2009 Ingo Renner, Henning Teek
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */package com.googlecode.chigs.web;

import org.apache.wicket.Request;
import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.authorization.strategies.role.Roles;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

import com.googlecode.chigs.domain.User;
import com.googlecode.chigs.repository.jpa.impl.UserServiceImpl;

/**
 * @author Henning Teek
 */
public class ChigsWebSession extends AuthenticatedWebSession {
	private final static Logger log = LoggerFactory.getLogger(ChigsWebSession.class);
	
    @SpringBean
    private AuthenticationManager authenticationManager;
    
    private User user;

	public ChigsWebSession(Request request) {
		super(request);
		InjectorHolder.getInjector().inject(this);
	}

	@Override
	public boolean authenticate(String username, String password) {
        boolean authenticated = false;
        try {
            Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
            SecurityContextHolder.getContext().setAuthentication(authentication);
            authenticated = authentication.isAuthenticated();
            
            if (authenticated && authentication.getPrincipal() instanceof UserServiceImpl) {
            	this.user = ((UserServiceImpl)authentication.getPrincipal()).getUser();
            }
        } catch (AuthenticationException e) {
            authenticated = false;
        }
        return authenticated;
	}

    @Override
    public Roles getRoles() {
        Roles roles = new Roles();
        if (isSignedIn()) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null) {
            	log.error("Unexpected: Authentication not found. No roles granted. SecurityContext="+SecurityContextHolder.getContext().toString());
            } else {
            	for (GrantedAuthority authority : authentication.getAuthorities()) {
            		roles.add(authority.getAuthority());
            	}
            }
        }
        return roles;
    }

	public User getUser() {
        return user;
	}
}
